﻿using System;
using System.IO;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using ASPNET = System.Web.UI.WebControls.WebParts;
using WebPart=System.Web.UI.WebControls.WebParts.WebPart;

namespace SKN
{
    /// <summary>
    /// Contains common method for Webpart
    /// </summary>
    public static class Webpart
    {
        /// <summary>
        /// Use this function to add 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="pageName"></param>
        /// <param name="webpartDefinition"></param>
        /// <param name="zoneID"></param>
        public static void AddWebPart(SPWeb web, string pageName, string webpartDefinition, string zoneID)
        {
            XmlReader xr = XmlReader.Create(new StringReader(webpartDefinition));
            SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(pageName, PersonalizationScope.Shared);

            string errorMessage;

            WebPart webPart = wpMgr.ImportWebPart(xr, out errorMessage);

            wpMgr.AddWebPart(webPart, zoneID, 0);
            wpMgr.Web.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="pageName"></param>
        /// <param name="dwpFileName"></param>
        /// <param name="zoneID"></param>
        public static void AddWebPartUsingFileName(SPWeb web, string pageName, string dwpFileName, string zoneID)
        {
            string errorMessage;

            using (SPSite site = web.Site)
            {
                using (SPWeb rootWeb = site.RootWeb)
                {
                    string url = rootWeb.Url + "/_catalogs/wp/" + dwpFileName;
                    XmlTextReader reader = new XmlTextReader(new StringReader(rootWeb.GetFileAsString(url)));
                    SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(pageName, PersonalizationScope.Shared);
                    WebPart webPart = (WebPart)wpMgr.ImportWebPart(reader, out errorMessage);
                    wpMgr.AddWebPart(webPart, zoneID, 1);
                    wpMgr.Web.Dispose();
                }
            }
        }

        /// <summary>
        /// Use to quickly create a definition file for ContentQueryWebpart 
        /// </summary>
        /// <param name="title">Webpart Title</param>
        /// <param name="html">HTML or Resource string</param>
        /// <returns></returns>
        public static string ContentQueryWebpartDwp(string title, string html)
        {
            string dwp =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<WebPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://schemas.microsoft.com/WebPart/v2"">
  <Title>" +
                title +
                @"</Title>
  <FrameType>Default</FrameType>
  <Description>Use for formatted text, tables, and images.</Description>
  <IsIncluded>true</IsIncluded>
  <ZoneID>Left</ZoneID>
  <PartOrder>0</PartOrder>
  <FrameState>Normal</FrameState>
  <Height />
  <Width />
  <AllowRemove>true</AllowRemove>
  <AllowZoneChange>true</AllowZoneChange>
  <AllowMinimize>true</AllowMinimize>
  <AllowConnect>true</AllowConnect>
  <AllowEdit>true</AllowEdit>
  <AllowHide>true</AllowHide>
  <IsVisible>true</IsVisible>
  <DetailLink />
  <HelpLink />
  <HelpMode>Modeless</HelpMode>
  <Dir>Default</Dir>
  <PartImageSmall />
  <MissingAssembly>Cannot import this Web Part.</MissingAssembly>
  <PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge>
  <IsIncludedFilter />
  <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
  <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
  <ContentLink xmlns=""http://schemas.microsoft.com/WebPart/v2/ContentEditor"" />
  <Content xmlns=""http://schemas.microsoft.com/WebPart/v2/ContentEditor""><![CDATA[" +
                html +
                @"]]></Content>
  <PartStorage xmlns=""http://schemas.microsoft.com/WebPart/v2/ContentEditor"" />
</WebPart>";

            return dwp;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="pageName"></param>
        /// <param name="title"></param>
        public static void DeleteWebPart(SPWeb web, string pageName, string title)
        {
            SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(pageName, PersonalizationScope.Shared);

            foreach (WebPart wp in wpMgr.WebParts)
            {
                if (wp != null && string.Equals(wp.Title, title, StringComparison.InvariantCultureIgnoreCase))
                {
                    wpMgr.DeleteWebPart(wp);
                    break;
                }
            }
            wpMgr.Web.Dispose();
        }


        /// <summary>
        ///  Use this method to quickly add a list view webpart
        /// </summary>
        /// <param name="web"></param>
        /// <param name="listName"></param>
        /// <param name="pageName"></param>
        /// <param name="zoneID"></param>
        public static void AddListViewWebPart(SPWeb web, string pageName, string listName, string zoneID)
        {
            SPList list = web.Lists[listName];

            var webPart = new ListViewWebPart
                              {
                                  WebId = web.ID,
                                  Title = listName,
                                  ListName = list.ID.ToString("B").ToUpper(),
                                  ViewGuid = list.DefaultView.ID.ToString("B").ToUpper(),
                              };

            SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(pageName, PersonalizationScope.Shared);

            wpMgr.AddWebPart(webPart, zoneID, 0);
            wpMgr.Web.Dispose();
        }
    }
}